<template>
  <div class="page-container">
    <h1>咨询列表</h1>

    <!-- 新闻列表 -->
    <el-table :data="newsList" style="width: 100%" stripe>
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column
        prop="content"
        label="内容"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button
            size="small"
            @click="handleEdit(scope.$index, scope.row)"
            type="primary"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            @click="deleteNews(scope.$index, scope.row)"
            type="danger"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      layout="prev, pager, next, jumper, ->, total"
      @size-change="fetchNewsList"
      @current-change="fetchNewsList"
    ></el-pagination>

    <!-- 添加/编辑新闻对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
      <el-form :model="newsForm" label-width="80px">
        <el-form-item label="标题">
          <el-input
            v-model="newsForm.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input
            v-model="newsForm.content"
            type="textarea"
            rows="4"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="关联房源">
          <el-select
            v-model="newsForm.houseId"
            placeholder="请选择关联房源"
            filterable
          >
            <el-option
              v-for="house in houseList"
              :key="house.id"
              :label="house.title"
              :value="house.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAction">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加新闻按钮 -->
    <el-button type="success" @click="handleAdd" style="margin-top: 20px"
      >添加</el-button
    >
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import api from "@/api";
import { ElMessage } from "element-plus";

const newsList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const houseList = ref([]);

async function getHousesByStatus() {
  try {
    const response = await api.house.getHousesByStatus(1);
    houseList.value = response.data;
    console.log(houseList.value);
  } catch (error) {
    console.error("数据加载失败:", error);
    ElMessage.error("数据加载失败: " + error.message);
  }
}
async function fetchNewsList() {
  try {
    const response = await api.news.getList({
      page: currentPage.value,
      size: pageSize.value,
    });
    newsList.value = response.data.data;
    total.value = response.data.total;
  } catch (error) {
    console.error("Failed to fetch news list:", error);
    ElMessage.error(error.response?.data?.message || "获取新闻列表失败");
  }
}

onMounted(() => {
  fetchNewsList();
  getHousesByStatus();
});

const dialogVisible = ref(false);
const isEditing = ref(false);
const currentNewsIndex = ref(null);
const newsForm = ref({
  id: null,
  title: "",
  content: "",
  houseId: null,
});

function handleAdd() {
  isEditing.value = false;
  newsForm.value.id = null;
  newsForm.value.title = "";
  newsForm.value.content = "";
  newsForm.value.houseId = null;
  dialogVisible.value = true;
}

function handleEdit(index, row) {
  isEditing.value = true;
  currentNewsIndex.value = index;
  newsForm.value.id = row.id;
  newsForm.value.title = row.title;
  newsForm.value.content = row.content;
  newsForm.value.houseId = row.houseId;
  dialogVisible.value = true;
}

async function confirmAction() {
  if (!newsForm.value.title) {
    ElMessage.warning("请填写标题");
    return;
  }
  if (!newsForm.value.content) {
    ElMessage.warning("请填写内容");
    return;
  }

  try {
    if (isEditing.value) {
      // 更新新闻
      await api.news.updateNews(newsForm.value.id, newsForm.value);
      Object.assign(newsList.value[currentNewsIndex.value], newsForm.value);
      ElMessage.success("更新成功");
    } else {
      // 添加新闻
      await api.news.addNews(newsForm.value);
      fetchNewsList(); // 刷新列表
      ElMessage.success("添加成功");
    }
    dialogVisible.value = false;
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error(error.response?.data?.message || "操作失败");
  }
}

async function deleteNews(index, row) {
  try {
    await api.news.deleteNews(row.id);
    newsList.value.splice(index, 1);
    total.value -= 1;
    ElMessage.success("删除成功");
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error(error.response?.data?.message || "删除失败");
  }
}

const dialogTitle = computed(() => (isEditing.value ? "编辑新闻" : "添加新闻"));
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.el-table th {
  background-color: #f5f7fa;
}

.el-table__row {
  height: 48px;
}

.el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fafafa;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

.el-button-circle {
  position: fixed;
  bottom: 40px;
  right: 40px;
}
</style>
